package com.ruoyi.system.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.MeetingRoom;
import com.ruoyi.system.service.IMeetingRoomService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.vo.MeetingRoomOrderReq;
import com.ruoyi.system.vo.MeetingRoomOrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MeetingRoomOrder;
import com.ruoyi.system.service.IMeetingRoomOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 会议室预约记录Controller
 *
 * @author hehonglin
 * @date 2022-04-09
 */
@RestController
@RequestMapping("/system/order")
@Api(tags = {"会议室预约"})
public class MeetingRoomOrderController extends BaseController {
    @Autowired
    private IMeetingRoomOrderService meetingRoomOrderService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IMeetingRoomService meetingRoomService;

    /**
     * 查询会议室预约记录列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(MeetingRoomOrder meetingRoomOrder) {
        startPage();
        meetingRoomOrder.setStatus(null);
        List<MeetingRoomOrder> list = meetingRoomOrderService.selectMeetingRoomOrderList(meetingRoomOrder);
        List<MeetingRoomOrderVo> collect = list.stream().map(e -> {
            MeetingRoomOrderVo meetingRoomOrderVo = new MeetingRoomOrderVo();
            BeanUtils.copyProperties(e, meetingRoomOrderVo);
            Long roomId = meetingRoomOrderVo.getRoomId();
            MeetingRoom meetingRoom = meetingRoomService.selectMeetingRoomByRoomId(roomId);
            meetingRoomOrderVo.setRoomName(meetingRoom.getRoomName());
            if (e.getOrderUserId() != null) {
                SysUser sysUser = userService.selectUserById(e.getOrderUserId());
                meetingRoomOrderVo.setOrderUserName(sysUser.getNickName());
            }
            if (e.getAuditUserId() != null) {
                SysUser sysUser = userService.selectUserById(e.getAuditUserId());
                meetingRoomOrderVo.setAuditUserName(sysUser.getNickName());
            }
            return meetingRoomOrderVo;

        }).collect(Collectors.toList());
        return getDataTable(collect);
    }

    /**
     * 导出会议室预约记录列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "会议室预约记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MeetingRoomOrder meetingRoomOrder) {
        List<MeetingRoomOrder> list = meetingRoomOrderService.selectMeetingRoomOrderList(meetingRoomOrder);
        ExcelUtil<MeetingRoomOrder> util = new ExcelUtil<MeetingRoomOrder>(MeetingRoomOrder.class);
        util.exportExcel(response, list, "会议室预约记录数据");
    }

    /**
     * 获取会议室预约记录详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(meetingRoomOrderService.selectMeetingRoomOrderById(id));
    }

    /**
     * 新增会议室预约记录
     */
//    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "管理员会议室预约记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MeetingRoomOrder meetingRoomOrder) {
        return toAjax(meetingRoomOrderService.insertMeetingRoomOrder(meetingRoomOrder));
    }


    //    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "用户预约会议室", businessType = BusinessType.INSERT)
    @PostMapping("/user")
    @ApiOperation(value = "用户预约会议室")
    public AjaxResult userAdd(@RequestBody MeetingRoomOrderReq meetingRoomOrderReq) {
        meetingRoomOrderReq.setOrderUserId(getUserId());
        meetingRoomOrderReq.setOrderTime(DateUtils.getNowDate());
        Date time = meetingRoomOrderReq.getTime();
        meetingRoomOrderReq.setStartTime(DateUtil.beginOfDay(time));
        meetingRoomOrderReq.setEndTime(DateUtil.offsetMinute(DateUtil.beginOfDay(DateUtil.offsetDay(time, 1)), -1));

        MeetingRoomOrder meetingRoomOrder = new MeetingRoomOrder();
        BeanUtils.copyProperties(meetingRoomOrderReq, meetingRoomOrder);
        return toAjax(meetingRoomOrderService.insertMeetingRoomOrder(meetingRoomOrder));
    }

    /**
     * 修改会议室预约记录
     */
//    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "会议室预约记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MeetingRoomOrder meetingRoomOrder) {
        return toAjax(meetingRoomOrderService.updateMeetingRoomOrder(meetingRoomOrder));
    }


    /**
     * 删除会议室预约记录
     */
//    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "会议室预约记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(meetingRoomOrderService.deleteMeetingRoomOrderByIds(ids));
    }

    //    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "取消会议室预约", businessType = BusinessType.DELETE)
    @DeleteMapping("/user")
    public AjaxResult remove(Long roomId, Long orderUserId, Date time) {
        if (!getUserId().equals(orderUserId)) {
            throw new RuntimeException("不是您预约的会议室，您不能取消");
        }
        //根据条件查询会议室预约记录
        MeetingRoomOrder orderByTimeAndId = meetingRoomOrderService.getOrderByTimeAndId(roomId, time);
        if (ObjectUtil.isNull(orderByTimeAndId)) {
            throw new RuntimeException("没有可取消的预约");
        }
        return toAjax(meetingRoomOrderService.deleteMeetingRoomOrderById(orderByTimeAndId.getId()));
    }

    /**
     * 通过审核
     */

    @Log(title = "通过审核", businessType = BusinessType.UPDATE)
    @PutMapping("/pass")
    public AjaxResult pass(@RequestBody MeetingRoomOrder meetingRoomOrder) {
        MeetingRoomOrder param = new MeetingRoomOrder();
        param.setAuditTime(DateUtils.getNowDate());
        param.setAuditUserId(getUserId());
        param.setId(meetingRoomOrder.getId());
        param.setStatus(meetingRoomOrder.getStatus());
        return toAjax(meetingRoomOrderService.updateMeetingRoomOrder(param));
    }
}
